package day04;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;

/**
 * @Description: 水位线测试
 * @Author: ZYX
 * @Date: 2022/2/11 16:14
 * @Version: 1.0
 */
public class Demo04 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        env.socketTextStream("192.168.0.177",9999)
                .map(new MapFunction<String, Tuple2<String,Long>>() {
                    @Override
                    public Tuple2<String, Long> map(String inputStr) throws Exception {
                        String[] strings = inputStr.split(" ");
                        return Tuple2.of(strings[0],Long.parseLong(strings[1])*1000L);
                    }
                })
                // 每隔200ms的机器时间，插入一次水位线
                .assignTimestampsAndWatermarks(
                        // 最大延迟时间设置为5s
                        WatermarkStrategy.<Tuple2<String,Long>>forBoundedOutOfOrderness(Duration.ofSeconds(5L))
                        .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String,Long>>() {
                            @Override
                            public long extractTimestamp(Tuple2<String, Long> stringLongTuple2, long l) {
                                // 告诉flink时间是哪个字段
                                return stringLongTuple2.f1;
                            }
                        })
                ).keyBy(obj -> obj.f0)
                // 5s的事件窗口滚动时间
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void process(String key, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {
                        long start = context.window().getStart();
                        long end = context.window().getEnd();
                        // 迭代器中共有多少条数据
                        long count = elements.spliterator().getExactSizeIfKnown();
                        out.collect("用户：" + key + " 在窗口" +
                                "" + new Timestamp(start) + "~" + new Timestamp(end) + "" +
                                "中的pv次数是：" + count);
                    }
                }).print();

        env.execute();
    }

}
